/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Income;
import com.jeeplus.modules.ap.entity.Yue;
import com.jeeplus.modules.ap.service.YueService;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Recel;
import com.jeeplus.modules.ap.service.RecelService;

/**
 * 回执结算Controller
 * @author 李超辉
 * @version 2018-04-24
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/recel")
public class RecelController extends BaseController {

	@Autowired
	private RecelService recelService;
	@Autowired
	private YueService yueService;
	@ModelAttribute
	public Recel get(@RequestParam(required=false) String id) {
		Recel entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = recelService.get(id);
		}
		if (entity == null){
			entity = new Recel();
		}
		return entity;
	}
	
	/**
	 * 回执结算列表页面
	 */
	@RequiresPermissions("ap:recel:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/recelList";
	}
	/**
	 * 回执结算列表页面
	 */
	@RequiresPermissions("ap:recel:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/2/recelList";
	}

//		/**
//	 * 回执结算列表数据
//	 */
//	@ResponseBody
//	@RequestMapping(value = "data")
//	public String data(Recel r, HttpServletRequest request,String min,String max,String pro,String code,String person,String card,String s,String receipt) {
//		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
//			r.setPro(pro);
//		}else{
//			if(!UserUtils.getUseroffice().equals("总部")){
//				r.setPro(UserUtils.getUseroffice());
//			}
//		}
//		r.setMinDate(min);
//		r.setMax(max);
//		r.setCode(code);
//		r.setPerson(person);
//		r.setCard(card);
//		r.setStatus(s);
//		r.setReceipt(receipt);
//		List<Recel> list=recelService.findList(r);
//		double hd=0.0;
//		double xj=0.0;
//		double yk=0.0;
//		double zje=0.0;
//		String ids="";
//		for(Recel re:list){
//            hd+=Double.parseDouble(re.getSfhd());
//			xj+=Double.parseDouble(re.getMoney());
//			yk+=Double.parseDouble(re.getOil());
//			zje+=Double.parseDouble(re.getSfzje());
//			ids+=re.getId()+",";
//
//		}
//		r.setSfhd(hd+"");
//		r.setMoney(xj+"");
//		r.setOil(yk+"");
//		r.setSfzje(zje+"");
//		r.setMax(ids);
//		list.add(r);
//		Gson g=new Gson();
//		return g.toJson(list).toString();
//	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Recel> list =new ArrayList<Recel>();
		for(String id:idd){
			list.add(recelService.get(id));
		}

		Export e=new Export();
		e.exportrecel(response,list);
	}
	/**
	 * 收入列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Recel recel, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			recel.setPro(pro);}
		Page<Recel> page = recelService.findPage(new Page<Recel>(request, response), recel);
		return getBootstrapData(page);
	}
	/**
	 * 收入列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Recel recel, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			recel.setPro(pro);}
			recel.setStatus("已入账");
		Page<Recel> page = recelService.findPage(new Page<Recel>(request, response), recel);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑回执结算表单页面
	 */
	@RequiresPermissions(value={"ap:recel:view","ap:recel:add","ap:recel:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Recel recel, Model model) {
		String pro= UserUtils.getUseroffice();
		if(pro!="总部"){
			recel.setPro(pro);
		}
		recel.setStatus("未过账");
		model.addAttribute("recel", recel);
		return "modules/ap/recelForm";
	}

	/**
	 * 保存回执结算
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:recel:add","ap:recel:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Recel recel, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
		String s=request.getParameter("date");
		String fk=request.getParameter("jsdate");
		recel.setDate(sim.parse(s));
		recel.setJsdate(sim.parse(fk));
		if (!beanValidator(model, recel)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		NumberFormat nf = NumberFormat.getInstance();
		double htzje=Double.parseDouble(recel.getHdht())+Double.parseDouble(recel.getHzht())+Double.parseDouble(recel.getHzxy());
		double zj=Double.parseDouble(recel.getSfzje())-htzje;
		recel.setZj(nf.format(zj).replaceAll(",",""));
		recel.setHtzje(nf.format(htzje).replaceAll(",",""));
		recelService.save(recel);//新建或者编辑保存

		j.setSuccess(true);
		j.setMsg("保存回执结算成功");
		return j;
	}

	/**
	 * 确认入账
	 */
	@ResponseBody
	@RequestMapping(value = "rz")
	public AjaxJson rz(Recel recel, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		NumberFormat nf = NumberFormat.getInstance();
		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		yue.setXj(nf.format(Double.parseDouble(yue.getXj())-Double.parseDouble(recel.getSfhd())-Double.parseDouble(recel.getMoney())).replaceAll(",",""));
		yue.setYk(nf.format(Double.parseDouble(yue.getYk())-Double.parseDouble(recel.getOil())).replaceAll(",",""));
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())-Double.parseDouble(recel.getSfhd())-Double.parseDouble(recel.getMoney())-Double.parseDouble(recel.getOil())).replaceAll(",",""));
		yueService.save(yue);
		recel.setStatus("已入账");
		recel.setRz(new Date());
		recelService.save(recel);
		j.setMsg("确认入账成功");
		return j;
	}
	/**
	 * 删除回执结算
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	public AjaxJson delete(Recel recel, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		recelService.delete(recel);
		j.setMsg("删除回执结算成功");
		return j;
	}
	
	/**
	 * 批量删除回执结算
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			recelService.delete(recelService.get(id));
		}
		j.setMsg("删除回执结算成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:recel:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Recel recel, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "回执结算"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Recel> page = recelService.findPage(new Page<Recel>(request, response, -1), recel);
    		new ExportExcel("回执结算", Recel.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出回执结算记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:recel:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Recel> list = ei.getDataList(Recel.class);
			for (Recel recel : list){
				try{
					recelService.save(recel);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条回执结算记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条回执结算记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入回执结算失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/recel/?repage";
    }
	
	/**
	 * 下载导入回执结算数据模板
	 */
	@RequiresPermissions("ap:recel:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "回执结算数据导入模板.xlsx";
    		List<Recel> list = Lists.newArrayList(); 
    		new ExportExcel("回执结算数据", Recel.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/recel/?repage";
    }

}